#include "StdAfx.h"
#include "TPTools.h"
#include "atlwfile.h"
#include "CXml/Xml.h"
#include "inline.h"

namespace TPTools
{
	BOOL CryptFile(LPCTSTR lpszMP3, LPCTSTR lpszIndex, LPCTSTR lpszOut)
	{
		using namespace JWXml;

		const UINT BUFFER_LEN = 1024;

		BOOL bResult = FALSE;

		CFile fMP3, fIndex, fOut;

		char buf[BUFFER_LEN];
		DWORD dwRead = 0;

		if ( fMP3.Open(lpszMP3) && fIndex.Open(lpszIndex)
			 && fOut.Open(lpszOut, GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS) )
		{
			do 
			{
				if ( fMP3.Read(buf, BUFFER_LEN, &dwRead) )
				{
					for ( DWORD dw = 0; dw < dwRead; ++dw )
					{
						buf[dw] = reverse(buf[dw]);
					}
					fOut.Write(buf, dwRead);
				}
			} while ( 0 != dwRead );

			CXml xml;

			if ( xml.Open(lpszIndex) )
			{
				CString strXml(xml.GetXml());
				DWORD dwLength = strXml.GetLength() * sizeof(TCHAR);

				fOut.Write((LPCTSTR)strXml, dwLength);
				fOut.Write(&dwLength, sizeof(DWORD));
			}
		}

		return bResult;
	}
}
